package chap2.Application1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import util.Constants;

public class HttpServer1 {

	private boolean shutdown = false;

	public void await() {
		ServerSocket serverSocket = null;

		try {
			serverSocket = new ServerSocket(Constants.PORT, 1, InetAddress.getByName("127.0.0.1"));
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			System.exit(1);
		}

		while (!shutdown) {
			Socket socket = null;
			InputStream input;
			OutputStream output;

			try {
				System.out.println("start up ...");
				socket = serverSocket.accept();
				input = socket.getInputStream();
				output = socket.getOutputStream();

				// create Request object and parse
				Request request = new Request(input);
				request.parse();

				// create Response object
				Response response = new Response(output);
				response.setRequest(request);
				
				if (request.getUri().startsWith("/servlet/")) {
					ServletProcessor1 processor = new ServletProcessor1();
					processor.process(request, response);
				}else {
					StaticResourceProcessor processor = new StaticResourceProcessor();
					processor.process(request, response);
				}
				
				socket.close();
				shutdown = request.getUri().equals(Constants.SHUTDOWN_COMMAND);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.exit(1);
			}
		}
	}
	
	/**
	 * test static  url = http://localhost:8090/index.html
	 * test servlet url = http://localhost:8090/servlet/util.PrimitiveServlet
	 * @param args
	 */
	public static void main(String[] args) {
		HttpServer1 server = new HttpServer1();
		server.await();
	}
}
